package main

import (
	"io"
	"log"
	"net/http"
	"net/url"
)

/**
反向代理
*/
func main() {
	http.HandleFunc("/", handler)
	log.Printf("Starting Serve Running At :" + port)
	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		log.Fatal(err)
	}
}

var (
	proxy_addr = "http://127.0.0.1:2003"
	port       = "2002"
)

func handler(rw http.ResponseWriter, req *http.Request) {
	// 1、解析代理地址，并更改请求体协议和主机
	proxy, err := url.Parse(proxy_addr)
	req.URL.Scheme = proxy.Scheme
	req.URL.Host = proxy.Host

	// 2、请求下游
	transport := http.DefaultTransport
	res, err := transport.RoundTrip(req)
	if err != nil {
		log.Fatal(err)
		return
	}

	// 3、内容反馈给上游
	for key, value := range res.Header {
		for _, v := range value {
			rw.Header().Set(key, v)
		}
	}
	io.Copy(rw, res.Body)
	defer res.Body.Close()
}
